import Fastify from 'fastify'
import cors from '@fastify/cors'
import jwt from '@fastify/jwt'
import { fileURLToPath } from 'url'
import { dirname, join } from 'path'
import { readFileSync } from 'fs'
import { initDB, getDB } from '../../shared/db/index.js'
import * as db from '../../shared/db/queries.js'
import * as adDb from '../../shared/db/ad-queries.js'
import * as favoriteDb from '../../shared/db/favorite-queries.js'
import * as historyDb from '../../shared/db/history-queries.js'
import * as userDb from '../../shared/db/user-queries.js'

const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)

// 读取环境变量
const env = {}
try {
  const envFile = readFileSync(join(__dirname, '../.env'), 'utf-8')
  envFile.split('\n').forEach(line => {
    const [key, ...values] = line.split('=')
    if (key && values.length) {
      env[key.trim()] = values.join('=').trim()
    }
  })
} catch (e) {
  console.log('未找到 .env 文件，使用默认配置')
}

const PORT = parseInt(env.PORT || process.env.PORT || '3001')
const JWT_SECRET = env.JWT_SECRET || process.env.JWT_SECRET || 'change-this-secret'
const ADMIN_USERNAME = env.ADMIN_USERNAME || process.env.ADMIN_USERNAME || 'admin'
const ADMIN_PASSWORD = env.ADMIN_PASSWORD || process.env.ADMIN_PASSWORD || 'admin123'
const API_KEY = env.API_KEY || process.env.API_KEY || 'your-api-key'

// 初始化数据库
initDB()

// 创建 Fastify 实例
const fastify = Fastify({
  logger: true
})

// 注册 CORS
fastify.register(cors, {
  origin: true,
  credentials: true
})

// 注册 JWT
fastify.register(jwt, {
  secret: JWT_SECRET
})

// 认证装饰器
const authenticate = async (request, reply) => {
  try {
    await request.jwtVerify()
  } catch (err) {
    reply.code(401).send({ error: '未授权访问' })
  }
}

// API Key 验证装饰器
const verifyApiKey = async (request, reply) => {
  const apiKey = request.headers['x-api-key']
  if (apiKey !== API_KEY) {
    reply.code(401).send({ error: '无效的 API Key' })
  }
}

// 响应格式插件
fastify.addHook('onSend', async (request, reply, payload) => {
  // 如果已经是字符串，尝试解析
  if (typeof payload === 'string') {
    try {
      payload = JSON.parse(payload)
    } catch (e) {
      // 不是 JSON，直接返回
      return payload
    }
  }
  
  // 处理对象类型的响应
  if (typeof payload === 'object' && payload !== null) {
    // 如果有 error 字段，说明是错误响应
    if (payload.error) {
      return JSON.stringify({
        code: reply.statusCode === 200 ? 400 : reply.statusCode,
        message: payload.error || 'error',
        data: null
      })
    }
    
    // 如果已经有 code 字段，说明已经格式化过了，直接返回
    if (payload.code !== undefined) {
      return JSON.stringify(payload)
    }
    
    // 正常响应，包装成统一格式
    return JSON.stringify({
      code: reply.statusCode === 200 ? 200 : reply.statusCode,
      message: reply.statusCode === 200 ? 'success' : 'error',
      data: payload
    })
  }
  
  return payload
})

// 健康检查
fastify.get('/health', async (request, reply) => {
  return { status: 'ok', timestamp: new Date().toISOString() }
})

// ============ 认证接口 ============

fastify.post('/admin/auth/login', async (request, reply) => {
  try {
    const { username, password } = request.body
    
    if (username === ADMIN_USERNAME && password === ADMIN_PASSWORD) {
      const token = fastify.jwt.sign({ username, role: 'admin' })
      return { token }
    }
    
    reply.code(401)
    return { error: '用户名或密码错误' }
  } catch (error) {
    fastify.log.error(error)
    reply.code(500)
    return { error: error.message }
  }
})

// ============ 分类管理接口 ============

fastify.get('/admin/categories', { preHandler: authenticate }, async (request, reply) => {
  try {
    const { page = 1, pageSize = 20, status } = request.query
    
    const options = {
      page: parseInt(page),
      pageSize: parseInt(pageSize)
    }
    
    if (status !== undefined) {
      options.status = parseInt(status)
    }
    
    const result = db.getCategoriesForAdmin(options)
    return result
  } catch (error) {
    fastify.log.error(error)
    reply.code(500)
    return { error: error.message }
  }
})

fastify.post('/admin/categories', { preHandler: authenticate }, async (request, reply) => {
  try {
    const { name, slug, description, sort = 0 } = request.body
    
    if (!name || !slug) {
      reply.code(400)
      return { error: '名称和标识不能为空' }
    }

    try {
      const category = db.createCategory({ name, slug, description, sort })
      return category
    } catch (error) {
      if (error.message.includes('UNIQUE constraint')) {
        reply.code(400)
        return { error: '标识已存在' }
      }
      throw error
    }
  } catch (error) {
    fastify.log.error(error)
    reply.code(500)
    return { error: error.message }
  }
})

fastify.put('/admin/categories/:id', { preHandler: authenticate }, async (request, reply) => {
  try {
    const { id } = request.params
    const data = request.body

    const category = db.updateCategory(parseInt(id), data)
    return category
  } catch (error) {
    fastify.log.error(error)
    reply.code(500)
    return { error: error.message }
  }
})

fastify.delete('/admin/categories/:id', { preHandler: authenticate }, async (request, reply) => {
  try {
    const { id } = request.params
    
    const result = db.deleteCategory(parseInt(id))
    return result
  } catch (error) {
    fastify.log.error(error)
    reply.code(400)
    return { error: error.message }
  }
})

// ============ 图片管理接口 ============

fastify.get('/admin/images', { preHandler: authenticate }, async (request, reply) => {
  try {
    const { page = 1, pageSize = 20, categoryId, status, keyword } = request.query
    
    const options = {
      page: parseInt(page),
      pageSize: parseInt(pageSize)
    }
    
    if (categoryId) options.categoryId = parseInt(categoryId)
    if (status !== undefined) options.status = parseInt(status)
    if (keyword) options.keyword = keyword

    const result = db.getImagesForAdmin(options)
    return result
  } catch (error) {
    fastify.log.error(error)
    reply.code(500)
    return { error: error.message }
  }
})

fastify.post('/admin/images', { preHandler: authenticate }, async (request, reply) => {
  try {
    const { title, url, thumbnail, categoryId, width, height, size } = request.body
    
    if (!title || !url || !categoryId) {
      reply.code(400)
      return { error: '标题、图片地址和分类不能为空' }
    }

    const image = db.createImage({
      title,
      url,
      thumbnail,
      categoryId: parseInt(categoryId),
      width: width ? parseInt(width) : null,
      height: height ? parseInt(height) : null,
      size: size ? parseInt(size) : null,
      status: 1 // 默认上架
    })

    return image
  } catch (error) {
    fastify.log.error(error)
    reply.code(500)
    return { error: error.message }
  }
})

// 批量创建图片（脚本接口，支持 API Key）
fastify.post('/admin/images/batch', { preHandler: [async (req, reply) => {
  const token = req.headers.authorization?.replace('Bearer ', '')
  const apiKey = req.headers['x-api-key']
  
  if (apiKey === API_KEY) {
    return // API Key 验证通过
  }
  
  if (token) {
    try {
      await req.jwtVerify()
      return // JWT 验证通过
    } catch (e) {
      // JWT 验证失败，继续检查 API Key
    }
  }
  
  reply.code(401).send({ error: '需要认证或 API Key' })
}] }, async (request, reply) => {
  try {
    const { images } = request.body
    
    if (!Array.isArray(images) || images.length === 0) {
      reply.code(400)
      return { error: '图片数组不能为空' }
    }

    const result = db.batchCreateImages(images)
    return result
  } catch (error) {
    fastify.log.error(error)
    reply.code(500)
    return { error: error.message }
  }
})

fastify.put('/admin/images/:id', { preHandler: authenticate }, async (request, reply) => {
  try {
    const { id } = request.params
    const data = request.body

    // 转换数字字段
    if (data.categoryId !== undefined) data.categoryId = parseInt(data.categoryId)
    if (data.width !== undefined) data.width = parseInt(data.width)
    if (data.height !== undefined) data.height = parseInt(data.height)
    if (data.size !== undefined) data.size = parseInt(data.size)
    if (data.status !== undefined) data.status = parseInt(data.status)

    const image = db.updateImage(parseInt(id), data)
    return image
  } catch (error) {
    fastify.log.error(error)
    reply.code(500)
    return { error: error.message }
  }
})

fastify.delete('/admin/images/:id', { preHandler: authenticate }, async (request, reply) => {
  try {
    const { id } = request.params

    const result = db.deleteImage(parseInt(id))
    return result
  } catch (error) {
    fastify.log.error(error)
    reply.code(500)
    return { error: error.message }
  }
})

fastify.put('/admin/images/:id/status', { preHandler: authenticate }, async (request, reply) => {
  try {
    const { id } = request.params
    const { status } = request.body

    if (status !== 0 && status !== 1) {
      reply.code(400)
      return { error: '状态值必须是 0 或 1' }
    }

    db.updateImage(parseInt(id), { status: parseInt(status) })
    return { message: '操作成功' }
  } catch (error) {
    fastify.log.error(error)
    reply.code(500)
    return { error: error.message }
  }
})

fastify.post('/admin/images/batch-status', { preHandler: authenticate }, async (request, reply) => {
  try {
    const { ids, status } = request.body

    if (!Array.isArray(ids) || ids.length === 0) {
      reply.code(400)
      return { error: 'ID 数组不能为空' }
    }

    if (status !== 0 && status !== 1) {
      reply.code(400)
      return { error: '状态值必须是 0 或 1' }
    }

    const result = db.batchUpdateImageStatus(ids.map(id => parseInt(id)), parseInt(status))
    return result
  } catch (error) {
    fastify.log.error(error)
    reply.code(500)
    return { error: error.message }
  }
})

// ============ 应用配置管理接口 ============

// 获取应用配置（结构化格式）
fastify.get('/admin/config/app', { preHandler: authenticate }, async (request, reply) => {
  try {
    const config = adDb.getAppConfig()
    return config
  } catch (error) {
    fastify.log.error(error)
    reply.code(500)
    return { error: error.message }
  }
})

// 获取所有配置项（列表格式）
fastify.get('/admin/config/app/list', { preHandler: authenticate }, async (request, reply) => {
  try {
    const configs = adDb.getAllAppConfigs()
    return { list: configs, total: configs.length }
  } catch (error) {
    fastify.log.error(error)
    reply.code(500)
    return { error: error.message }
  }
})

// 更新单个配置项
fastify.put('/admin/config/app/:key', { preHandler: authenticate }, async (request, reply) => {
  try {
    const { key } = request.params
    const { value, description } = request.body

    if (value === undefined) {
      reply.code(400)
      return { error: '配置值不能为空' }
    }

    adDb.setAppConfig(key, value, description || '')
    return { message: '更新成功' }
  } catch (error) {
    fastify.log.error(error)
    reply.code(500)
    return { error: error.message }
  }
})

// 批量更新配置
fastify.post('/admin/config/app/batch', { preHandler: authenticate }, async (request, reply) => {
  try {
    const { configs } = request.body

    if (!Array.isArray(configs) || configs.length === 0) {
      reply.code(400)
      return { error: '配置数组不能为空' }
    }

    // 验证配置格式
    for (const config of configs) {
      if (!config.key || config.value === undefined) {
        reply.code(400)
        return { error: '配置项格式错误，必须包含 key 和 value' }
      }
    }

    adDb.batchUpdateAppConfig(configs)
    return { message: '批量更新成功' }
  } catch (error) {
    fastify.log.error(error)
    reply.code(500)
    return { error: error.message }
  }
})

// 删除配置项
fastify.delete('/admin/config/app/:key', { preHandler: authenticate }, async (request, reply) => {
  try {
    const { key } = request.params

    adDb.deleteAppConfig(key)
    return { message: '删除成功' }
  } catch (error) {
    fastify.log.error(error)
    reply.code(500)
    return { error: error.message }
  }
})

// ============ 用户管理接口 ============

// 获取用户列表
fastify.get('/admin/users', { preHandler: authenticate }, async (request, reply) => {
  try {
    const { type, platform, status, page = 1, pageSize = 20 } = request.query
    
    const result = userDb.getUsers({
      type: type || undefined,
      platform: platform || undefined,
      status: status ? parseInt(status) : undefined,
      page: parseInt(page),
      pageSize: parseInt(pageSize)
    })
    
    return result
  } catch (error) {
    fastify.log.error(error)
    reply.code(500)
    return { error: error.message }
  }
})

// 获取用户详情
fastify.get('/admin/users/:userId', { preHandler: authenticate }, async (request, reply) => {
  try {
    const { userId } = request.params
    const user = userDb.getUserByUserId(userId)
    
    if (!user) {
      reply.code(404)
      return { error: '用户不存在' }
    }
    
    return user
  } catch (error) {
    fastify.log.error(error)
    reply.code(500)
    return { error: error.message }
  }
})

// 更新用户状态
fastify.put('/admin/users/:userId/status', { preHandler: authenticate }, async (request, reply) => {
  try {
    const { userId } = request.params
    const { status } = request.body
    
    if (status === undefined) {
      reply.code(400)
      return { error: '状态不能为空' }
    }
    
    const success = userDb.updateUserStatus(userId, parseInt(status))
    
    if (success) {
      return { success: true, message: '更新成功' }
    } else {
      reply.code(404)
      return { error: '用户不存在' }
    }
  } catch (error) {
    fastify.log.error(error)
    reply.code(500)
    return { error: error.message }
  }
})

// 删除用户
fastify.delete('/admin/users/:userId', { preHandler: authenticate }, async (request, reply) => {
  try {
    const { userId } = request.params
    const success = userDb.deleteUser(userId)
    
    if (success) {
      return { success: true, message: '删除成功' }
    } else {
      reply.code(404)
      return { error: '用户不存在' }
    }
  } catch (error) {
    fastify.log.error(error)
    reply.code(500)
    return { error: error.message }
  }
})

// 获取用户统计
fastify.get('/admin/users/stats', { preHandler: authenticate }, async (request, reply) => {
  try {
    const stats = userDb.getUserStats()
    return stats
  } catch (error) {
    fastify.log.error(error)
    reply.code(500)
    return { error: error.message }
  }
})

// ============ 收藏管理接口 ============

// 获取收藏列表（管理员）
fastify.get('/admin/favorites', { preHandler: authenticate }, async (request, reply) => {
  try {
    const { userId, imageId, page = 1, pageSize = 20 } = request.query
    
    const result = favoriteDb.getFavoriteStats({
      userId: userId || undefined,
      imageId: imageId ? parseInt(imageId) : undefined,
      page: parseInt(page),
      pageSize: parseInt(pageSize)
    })
    
    return result
  } catch (error) {
    fastify.log.error(error)
    reply.code(500)
    return { error: error.message }
  }
})

// 删除收藏（管理员）
fastify.delete('/admin/favorites/:id', { preHandler: authenticate }, async (request, reply) => {
  try {
    const { id } = request.params
    const db = getDB()
    
    const stmt = db.prepare('DELETE FROM Favorite WHERE id = ?')
    const result = stmt.run(parseInt(id))
    
    if (result.changes > 0) {
      return { success: true, message: '删除成功' }
    } else {
      reply.code(404)
      return { error: '收藏记录不存在' }
    }
  } catch (error) {
    fastify.log.error(error)
    reply.code(500)
    return { error: error.message }
  }
})

// 获取收藏统计
fastify.get('/admin/favorites/stats', { preHandler: authenticate }, async (request, reply) => {
  try {
    const db = getDB()
    
    // 总收藏数
    const totalStmt = db.prepare('SELECT COUNT(*) as total FROM Favorite')
    const total = totalStmt.get().total
    
    // 今日新增收藏数
    const todayStmt = db.prepare(`
      SELECT COUNT(*) as count
      FROM Favorite
      WHERE date(createdAt) = date('now')
    `)
    const today = todayStmt.get().count
    
    // 最受欢迎的图片（收藏数最多）
    const popularStmt = db.prepare(`
      SELECT 
        i.id,
        i.title,
        COUNT(f.id) as favoriteCount
      FROM Image i
      LEFT JOIN Favorite f ON i.id = f.imageId
      WHERE i.status = 1
      GROUP BY i.id
      ORDER BY favoriteCount DESC
      LIMIT 10
    `)
    const popular = popularStmt.all()
    
    return {
      total,
      today,
      popular
    }
  } catch (error) {
    fastify.log.error(error)
    reply.code(500)
    return { error: error.message }
  }
})

// ============ 浏览历史管理接口 ============

// 获取浏览历史列表（管理员）
fastify.get('/admin/history', { preHandler: authenticate }, async (request, reply) => {
  try {
    const { userId, imageId, page = 1, pageSize = 20 } = request.query
    
    const result = historyDb.getViewHistoryStats({
      userId: userId || undefined,
      imageId: imageId ? parseInt(imageId) : undefined,
      page: parseInt(page),
      pageSize: parseInt(pageSize)
    })
    
    return result
  } catch (error) {
    fastify.log.error(error)
    reply.code(500)
    return { error: error.message }
  }
})

// 删除浏览历史（管理员）
fastify.delete('/admin/history/:id', { preHandler: authenticate }, async (request, reply) => {
  try {
    const { id } = request.params
    const db = getDB()
    
    const stmt = db.prepare('DELETE FROM ViewHistory WHERE id = ?')
    const result = stmt.run(parseInt(id))
    
    if (result.changes > 0) {
      return { success: true, message: '删除成功' }
    } else {
      reply.code(404)
      return { error: '浏览历史记录不存在' }
    }
  } catch (error) {
    fastify.log.error(error)
    reply.code(500)
    return { error: error.message }
  }
})

// 获取浏览历史统计
fastify.get('/admin/history/stats', { preHandler: authenticate }, async (request, reply) => {
  try {
    const db = getDB()
    
    // 总浏览数
    const totalStmt = db.prepare('SELECT COUNT(*) as total FROM ViewHistory')
    const total = totalStmt.get().total
    
    // 今日浏览数
    const todayStmt = db.prepare(`
      SELECT COUNT(*) as count
      FROM ViewHistory
      WHERE date(viewedAt) = date('now')
    `)
    const today = todayStmt.get().count
    
    // 最受欢迎的图片（浏览数最多）
    const popularStmt = db.prepare(`
      SELECT 
        i.id,
        i.title,
        COUNT(h.id) as viewCount
      FROM Image i
      LEFT JOIN ViewHistory h ON i.id = h.imageId
      WHERE i.status = 1
      GROUP BY i.id
      ORDER BY viewCount DESC
      LIMIT 10
    `)
    const popular = popularStmt.all()
    
    return {
      total,
      today,
      popular
    }
  } catch (error) {
    fastify.log.error(error)
    reply.code(500)
    return { error: error.message }
  }
})

// 启动服务器
const start = async () => {
  try {
    await fastify.listen({ port: PORT, host: '0.0.0.0' })
    console.log(`🚀 Admin 服务已启动: http://localhost:${PORT}`)
    console.log(`📝 默认管理员账号: ${ADMIN_USERNAME} / ${ADMIN_PASSWORD}`)
  } catch (err) {
    fastify.log.error(err)
    process.exit(1)
  }
}

start()
